<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>.NET中PasswordDeriveBytes.CryptDeriveKey的Java实现 - macdfree&#39;s blog</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="macd" /><meta name="description" content=".NET中PasswordDeriveBytes.CryptDeriveKey的Java实现" />
<meta name="keywords" content="PasswordDeriveBytes, CryptDeriveKey, .NET, Java" />



<meta name="baidu-site-verification" content="Ak74Sk61bk" />
<meta name="google-site-verification" content="fAeFHpkrhfFS8LxdzXy0EtAPcVStv0faGn238sRF3L8" />


<meta name="generator" content="Hugo 0.54.0" />


<link rel="canonical" href="/posts/dotnet%E4%B8%ADpasswordderivebytes.cryptderivekey%E7%9A%84java%E5%AE%9E%E7%8E%B0/" />

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">




<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>


<link href="/dist/even.min.css?v=3.1.1" rel="stylesheet">
<link href="/lib/fancybox/jquery.fancybox-3.1.20.min.css" rel="stylesheet">




<meta property="og:title" content=".NET中PasswordDeriveBytes.CryptDeriveKey的Java实现" />
<meta property="og:description" content=".NET中PasswordDeriveBytes.CryptDeriveKey的Java实现" />
<meta property="og:type" content="article" />
<meta property="og:url" content="/posts/dotnet%E4%B8%ADpasswordderivebytes.cryptderivekey%E7%9A%84java%E5%AE%9E%E7%8E%B0/" />
<meta property="article:published_time" content="2018-05-10T08:13:12&#43;08:00"/>
<meta property="article:modified_time" content="2018-05-10T08:13:12&#43;08:00"/>

<meta itemprop="name" content=".NET中PasswordDeriveBytes.CryptDeriveKey的Java实现">
<meta itemprop="description" content=".NET中PasswordDeriveBytes.CryptDeriveKey的Java实现">


<meta itemprop="datePublished" content="2018-05-10T08:13:12&#43;08:00" />
<meta itemprop="dateModified" content="2018-05-10T08:13:12&#43;08:00" />
<meta itemprop="wordCount" content="1527">



<meta itemprop="keywords" content="CryptDeriveKey," />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content=".NET中PasswordDeriveBytes.CryptDeriveKey的Java实现"/>
<meta name="twitter:description" content=".NET中PasswordDeriveBytes.CryptDeriveKey的Java实现"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">macdfree&#39;s blog</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">分类</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">标签</li>
      </a><a href="/archive/">
        <li class="mobile-menu-item">归档</li>
      </a>
  </ul>
</nav>
  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">macdfree&#39;s blog</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/archive/">归档</a>
      </li>
  </ul>
</nav>
    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">.NET中PasswordDeriveBytes.CryptDeriveKey的Java实现</h1>

      <div class="post-meta">
        <span class="post-time"> 2018-05-10 </span>
        <div class="post-category">
          
            <a href="/categories/java/"> java </a>
          
        </div>
        <span class="more-meta"> 约 1527 字 </span>
        <span class="more-meta"> 预计阅读 4 分钟 </span>
        <span id="busuanzi_container_page_pv" class="more-meta"> <span id="busuanzi_value_page_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次阅读 </span>
      </div>
    </header>

    
    
<div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
<ul>
<li><a href="#为什么要使用密钥生成器">为什么要使用密钥生成器</a></li>
<li><a href="#net中passwordderivebytes类介绍">.NET中PasswordDeriveBytes类介绍</a></li>
<li><a href="#java实现方式">Java实现方式</a></li>
</ul>
</nav>
  </div>
</div>

    
    <div class="post-content">
      <p>新老系统分别基于Java和.NET，老系统中使用<code>PasswordDeriveBytes.CryptDeriveKey</code>进行3DES密钥的生成。为实现新老系统的互操作性，需要使用Java实现密钥生成逻辑。</p>

<h1 id="为什么要使用密钥生成器">为什么要使用密钥生成器</h1>

<p>对于对称加密算法，需要使用一个密钥将明文加密为密文，那这个密钥如何产生呢？一个最简单的做法就是将用户提供的密码直接转成字节数组作为密钥。但这会导致如下问题：</p>

<ol>
<li>各种加密算法所要求的密钥长度不尽相同。以3DES为例，所需的密钥长度为192位，即需要用户提供24字节的密码，否则会导致密钥位数不够。还有一种做法是自动填充字符以满足密钥长度，这会导致密码中会有相同的字符进行加解密，使密文更容易被破解。</li>
<li>用户输入的密码一般只包含a-z，A-Z，0-9，也可能包含一些符合。这意味着每个字节只能使用70-75种可能的组合。另外，并不是每个符号都会使用偶数频率。在英语密码的单个字节中熵的各种估计值从1.3到4位不等。这意味着为了生成一个好的256位密钥，你需要一个长度为64到197字节的密码。</li>
</ol>

<p><a href="https://blogs.msdn.microsoft.com/shawnfa/2004/04/14/generating-a-key-from-a-password/">参考文档</a></p>

<h1 id="net中passwordderivebytes类介绍">.NET中PasswordDeriveBytes类介绍</h1>

<p>为了解决上述问题，.NET提供了PasswordDeriveBytes类进行密钥的生成，可以实现屏蔽不同加密算法所需密钥长度的不同，生成指定加密算法的合适密钥长度。示例代码如下：</p>

<pre><code class="language-c#">PasswordDeriveBytes pderiver = new PasswordDeriveBytes(&quot;password&quot;, null);
byte[] key = pderiver.CryptDeriveKey(&quot;TripleDES&quot;, &quot;SHA1&quot;, 0, new byte[8]);
</code></pre>

<p>通过查看PasswordDeriveBytes类源码发现，CryptDeriveKey方法最终是调用了微软的加密dll实现</p>

<pre><code class="language-c#">[System.Security.SecuritySafeCritical]  // auto-generated
public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
{
    if (keySize &lt; 0)
        throw new CryptographicException(Environment.GetResourceString(&quot;Cryptography_InvalidKeySize&quot;));

    int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm);
    if (algidhash == 0)
        throw new CryptographicException(Environment.GetResourceString(&quot;Cryptography_PasswordDerivedBytes_InvalidAlgorithm&quot;));
    int algid = X509Utils.NameOrOidToAlgId(algname, OidGroup.AllGroups);
    if (algid == 0)
        throw new CryptographicException(Environment.GetResourceString(&quot;Cryptography_PasswordDerivedBytes_InvalidAlgorithm&quot;));

    // Validate the rgbIV array
    if (rgbIV == null)
        throw new CryptographicException(Environment.GetResourceString(&quot;Cryptography_PasswordDerivedBytes_InvalidIV&quot;));

    byte[] key = null;
    DeriveKey(ProvHandle, algid, algidhash,
                _password, _password.Length, keySize &lt;&lt; 16, rgbIV, rgbIV.Length,
                JitHelpers.GetObjectHandleOnStack(ref key));
    return key;
}

//
// private methods
//
[System.Security.SecurityCritical]  // auto-generated
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void DeriveKey(SafeProvHandle hProv, int algid, int algidHash, byte[] password, int cbPassword, int dwFlags, byte[] IV, int cbIV, ObjectHandleOnStack retKey);
</code></pre>

<p><a href="https://referencesource.microsoft.com/#mscorlib/system/security/cryptography/passwordderivebytes.cs,69f601fc0efaa588,references">参考文档</a></p>

<h1 id="java实现方式">Java实现方式</h1>

<p>由于微软的加密dll并没有开源，所以Java中并没有PasswordDeriveBytes.CryptDeriveKey的官方实现。同时也查找了.NET的开源实现Mono中的相关源码，发现此方法也没有开源实现，见<a href="https://github.com/mono/mono/blob/07adebd8bf94f2c4310421460940fd6c873b24d5/mcs/class/referencesource/mscorlib/system/security/cryptography/passwordderivebytes.cs">mono源码</a>。</p>

<p>通过搜索，发现有和我遇到相同问题的解决方法，但经测试，发现并不能实现.NET和Java的互通。</p>

<p>最后尝试参考 <a href="https://groups.google.com/forum/#!topic/microsoft.public.security.crypto/GdZ3vbFrUxo">C++ implementation of CryptDeriveKey</a> 和 <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa379916(v=vs.85).aspx">CryptDeriveKey方法介绍</a> 自己实现密钥生成算法，算法说明如下：</p>

<blockquote>
<ol>
<li>Form a 64-byte buffer by repeating the constant 0x36 64 times. Let k be the length of the hash value that is represented by the input parameter hBaseData. Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData.</li>
<li>Form a 64-byte buffer by repeating the constant 0x5C 64 times. Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData.</li>
<li>Hash the result of step 1 by using the same hash algorithm as that used to compute the hash value that is represented by the hBaseData parameter.</li>
<li>Hash the result of step 2 by using the same hash algorithm as that used to compute the hash value that is represented by the hBaseData parameter.</li>
<li>Concatenate the result of step 3 with the result of step 4.</li>
<li>Use the first n bytes of the result of step 5 as the derived key.</li>
</ol>
</blockquote>

<p>按照此步骤进行实现后，经测试，发现部分字节会与正确字节相差1，例如：</p>

<pre><code class="language-js">// .NET
[212, 29, 193, 4, 11, 26, 237, 176, 53, 50, 159, 110, 57, 184, 185, 188, 229, 48, 73, 251, 199, 170, 248, 131]

// Java
[213, 28, 193, 4, 11, 26, 236, 176, 52, 50, 158, 110, 56, 185, 185, 188, 229, 49, 73, 251, 199, 171, 248, 131]
</code></pre>

<p>对字节二进制进行分析后发现可能是做了奇偶校验。具体逻辑为：如果二进制中1的个数为偶数，判断最低位为0时，将最低位设置为1，当最低位为1时，设置为0，保证1的个数为奇数。</p>

<p>结合上述逻辑，生成密钥代码如下：</p>

<pre><code class="language-java">private static byte[] sha1(byte[] password) {
    try {
        MessageDigest md = MessageDigest.getInstance(&quot;SHA-1&quot;);
        md.reset();
        return md.digest(password);
    }
    catch (NoSuchAlgorithmException nsae) {
        nsae.printStackTrace();
        return new byte[0];
    }
}

private static byte[] cryptDeriveKey(byte[] password) {

    byte[] buff1 = new byte[64];
    byte[] buff2 = new byte[64];
    Arrays.fill(buff1, (byte) 0x36);
    Arrays.fill(buff2, (byte) 0x5C);

    byte[] hash = sha1(password);

    for (int i = 0; i &lt; hash.length; i++) {
        buff1[i] ^= hash[i];
        buff2[i] ^= hash[i];
    }

    byte[] derivedKey = new byte[24];

    byte[] a = sha1(buff1);
    byte[] b = sha1(buff2);

    for (int i = 0; i &lt; 24; i++) {
        if (i &lt; a.length) {
            derivedKey[i] = parityOfOdd(a[i]);
        }
        else {
            derivedKey[i] = parityOfOdd(b[i - a.length]);
        }
    }

    return derivedKey;
}

private static byte parityOfOdd(byte b) {
    int k = 0x01;
    int count = 0;
    for (int i = 0; i &lt; 8; i++) {
        if ((b &amp; k) != 0) {
            count++;
        }
        k = k &lt;&lt; 1;
    }
    if (count % 2 == 0) {
        b = (byte) (b ^ 0x01);
        return b;
    }
    else {
        return b;
    }
}
</code></pre>
    </div>

    
    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">macd</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">2018-05-10</span>
  </p>
  
  
</div>

    
    
<div class="post-reward">
  <input type="checkbox" name="reward" id="reward" hidden />
  <label class="reward-button" for="reward">赞赏支持</label>
  <div class="qr-code">
    
    
      <label class="qr-code-image" for="reward">
        <img class="image" src="/img/reward/wechat-qr-code.png">
        <span>微信打赏</span>
      </label>
    
      <label class="qr-code-image" for="reward">
        <img class="image" src="/img/reward/alipay-qr-code.png">
        <span>支付宝打赏</span>
      </label>
  </div>
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
          <a href="/tags/cryptderivekey/">CryptDeriveKey</a>
          
        </div>

      
      <nav class="post-nav">
        
          <a class="prev" href="/posts/upsource%E4%BD%BF%E7%94%A8%E8%AE%B0%E5%BD%95/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">Upsource使用记录</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        
          <a class="next" href="/posts/ml/google%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">
            <span class="next-text nav-default">Google机器学习笔记</span>
            <span class="prev-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        
  <div id="comments-gitment"></div>
  <link rel="stylesheet" href="/lib/gitment/gitment-0.0.3.min.css">
    <script src="/lib/gitment/gitment-0.0.3.min.js"></script>
  <script type="text/javascript">
  const gitment = new Gitment({
    id: '2018-05-10 08:13:12 \x2b0800 \x2b0800',
    title: '.NET中PasswordDeriveBytes.CryptDeriveKey的Java实现',
    link: decodeURI(location.href),
    desc: '\x3cp\x3e新老系统分别基于Java和.NET，老系统中使用\x3ccode\x3ePasswordDeriveBytes.CryptDeriveKey\x3c\/code\x3e进行3DES密钥的生成。为实现新老系统的互操作性，需要使用Java实现密钥生成逻辑。\x3c\/p\x3e',
    owner: 'MACDfree',
    repo: 'gitment4',
    oauth: {
      client_id: '3de7eda9fae832753b25',
      client_secret: 'fb1c82c44491295195db0eb7a2d12af22dfcae29'
    }
  })
  gitment.render('comments-gitment')
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://github.com/imsun/gitment">comments powered by gitment.</a></noscript>
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:macdfree@163.com" class="iconfont icon-email" title="email"></a>
      <a href="https://github.com/MACDfree" class="iconfont icon-github" title="github"></a>
  <a href="/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  <div class="busuanzi-footer">
    <span id="busuanzi_container_site_pv"> 本站总访问量 <span id="busuanzi_value_site_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次 </span>
    <span class="division">|</span>
    <span id="busuanzi_container_site_uv"> 本站总访客数 <span id="busuanzi_value_site_uv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 人 </span>
  </div>

  <span class="copyright-year">
    &copy; 
    
      2014 - 
    2019
    <span class="heart">
      <i class="iconfont icon-heart"></i>
    </span>
    <span class="author">macd</span>
    <span class="division">|</span>
    <span style="margin-left: 5px;">
      <img alt="buildstatus" src="https://travis-ci.org/MACDfree/hugoblog.svg?branch=master">
    </span>
  </span>
</div>
    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
<script src="/lib/highlight/highlight.pack.js?v=20171001"></script><script type="text/javascript" src="/lib/jquery/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src="/lib/slideout/slideout-1.0.1.min.js"></script>
  <script type="text/javascript" src="/lib/fancybox/jquery.fancybox-3.1.20.min.js"></script>
<script type="text/javascript" src="/dist/even.min.js?v=3.1.1"></script>








</body>
</html>
